<template>
  <div class="app-container">
    <div class="app-container-table-border">
      <div class="header-title">
        <div>
          <span>选择报表：</span>
          <el-select class="cd-ml8 cd-mr8" v-model="queryParams.type" placeholder="" size="mini" style="width: 140px" @change="typeChange">
            <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
          <span v-if="qsInfo && qsInfo.beginDate"> {{ `当前期：${qsInfo.qhName}（${parseTime(qsInfo.beginDate, "{y}-{m}-{d}")} 至 ${parseTime(qsInfo.endDate, "{y}-{m}-{d}")}） ` }}</span>
        </div>
        <div class="display-right-btn">
          <el-button v-show="hasDownload" type="primary" plain size="mini" @click="onDownload">下载</el-button>
          <el-button v-show="hasDownload" type="primary" plain size="mini" @click="onPrint">打印</el-button>
          <el-button v-show="!reportId" type="warning" plain size="mini" @click="handleClose">返回</el-button>
        </div>
      </div>
      <div class="vue-office-docx-border">
        <vue-office-docx id="fileView" v-if="docx" :src="docx" @rendered="rendered" />
      </div>
    </div>
  </div>
</template>

<script>
import { saveAs } from "file-saver";
import { getReportFormPayment } from "@/api/ma/paymentReportForm";
//引入VueOfficeDocx组件
import VueOfficeDocx from "@vue-office/docx";
//引入相关样式
import "@vue-office/docx/lib/index.css";
import html2canvas from "html2canvas";

export default {
  name: "PaymentStatement",
  components: {
    VueOfficeDocx
  },
  props: {
    reportId: {
      type: [String, Number],
      export: ""
    }
  },
  data() {
    return {
      viewHeight: document.documentElement.scrollHeight - 120,
      docx: "",
      queryParams: {
        reportId: undefined,
        gysId: undefined,
        type: "1"
      },
      options: [
        {
          label: "封面",
          value: "1"
        },
        {
          label: "支付申请表",
          value: "2"
        },
        {
          label: "支付明细表",
          value: "3"
        },
        {
          label: "月度供货计算表",
          value: "4"
        }
      ],
      qsInfo: {},
      fileInfo: {
        url: "",
        blob: "",
        fileName: ""
      },
      hasDownload: false
    };
  },
  watch: {
    $route: {
      handler(to, from) {
        const reportId = to.query.reportId;
        if (reportId != this.queryParams.reportId) {
          this.queryParams.reportId = this.$route.query.reportId;
          this.init();
        }
      },
      deep: true, // 深度监听
      immediate: true // 第一次初始化渲染就可以监听到
    },
    reportId: {
      handler(val) {
        if (val && val != this.queryParams.reportId) {
          this.queryParams.reportId = val;
          this.init();
        }
      },
      deep: true, // 深度监听
      immediate: true // 第一次初始化渲染就可以监听到
    }
  },
  created() {},
  mounted() {
    this.doLayout();
    //根据屏幕缩放自动获取页面宽高
    window.onresize = () => {
      return (() => {
        this.doLayout();
      })();
    };
  },
  methods: {
    init(reportId) {
      if (reportId) {
        this.queryParams.reportId = reportId;
        // this.queryParams.gysId = gysId;
      }
      // 获取期号详情
      this.getQhInfo();
      // 获取文件
      this.handleExport();
    },
    getQhInfo() {
      getReportFormPayment(this.queryParams.reportId).then((response) => {
        this.qsInfo = response.data;
      });
    },
    typeChange() {
      this.handleExport();
    },
    /** 获取文件 */
    handleExport() {
      this.hasDownload = false;
      const info = this.options.find((item) => item.value == this.queryParams.type);
      this.download(
        "ma/reportFormPayment/importTemplate",
        {
          ...this.queryParams
        },
        `${info.label}_${new Date().getTime()}.docx`,
        {},
        true
      ).then((response) => {
        console.log(response);
        const { url } = response;
        this.docx = url;
        this.fileInfo = response;
      });
    },
    rendered() {
      console.log("渲染完成");
      this.hasDownload = true;
    },
    // 打印
    onPrint() {
      // this.generatePrint()
      let dom = document.getElementById("fileView");
      const newDom = dom.querySelector(".docx-wrapper");
      this.$print(newDom);
    },
    generatePrint() {
      return new Promise((resolve, reject) => {
        let reportItem = document.querySelectorAll(".docx-wrapper");
        const pageNumber = Math.floor((100 / 1) * 10) / 10;
        let nextData = null;
        if (pageNumber > 0) nextData = reportItem.entries();
        let div = document.createElement("div");
        const printPage = (value) => {
          // 生成打印的图片
          if (value.done) {
            // 结束
            console.log(div);
            this.$print(div);
            // document.body.appendChild(div);
            this.exportPercentage = 0;
            resolve();
          } else {
            html2canvas(value.value[1], {
              scale: 2,
              backgroundColor: "#ffffff",
              useCORS: true,
              scrollY: 0,
              scrollX: 0
              // width: 794,
              // height: 1123
            }).then((canvas) => {
              const imgData = canvas.toDataURL("image/jpeg", 1.0);
              let img = document.createElement("img");
              img.classList.add("printImg");
              img.src = imgData;
              div.appendChild(img);
              // // 进度条
              if (this.exportPercentage >= 100) this.exportPercentage = 100;
              else {
                let value = this.exportPercentage + pageNumber;
                value = Math.round(value, 1);
                this.exportPercentage = value;
              }
              // this.loadingChange();
              printPage(nextData.next());
            });
          }
        };
        if (nextData) printPage(nextData.next());
        else this.$message.warning("打印异常，请稍后重试");
      });
    },
    // 下载
    onDownload() {
      saveAs(this.fileInfo.blob, this.fileInfo.fileName);
    },
    doLayout() {
      this.viewHeight = document.documentElement.clientHeight - 120;
    },
    /** 返回按钮操作 */
    handleClose() {
      const obj = { path: "/material/paymentReportForm", query: { gysId: this.qsInfo.gysId, zdId: this.qsInfo.zdId } };
      this.$tab.closeOpenPage(obj);
    }
  }
};
</script>
<style lang="scss" scoped>
.app-container-table-border {
  position: relative;
  height: auto;
  min-height: calc(100vh - 105px);
}

.header-title {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin: 10px 0;
  font-size: 18px;
  // font-weight: 700;
}

.view {
  width: 100%;
  overflow-y: auto;
}

.pdf-bg {
  width: 100%;
  margin: 0 auto;
  overflow-y: auto;
  background-color: #808080;
}

.luckysheet {
  height: 100%;
  width: 80%;
}

.vue-office-docx-border {
  ::v-deep {
    .docx-wrapper {
      background-color: #ffffff;
      padding: 0;
    }

    .docx {
      box-shadow: 0 0 0px rgba(0, 0, 0, 0.5);
    }
  }
}
.vue-office-docx-border-none {
  display: none;
}
</style>
